package com.laundry.merchant.ui.statistics

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.laundry.merchant.databinding.FragmentStatisticsBinding

class StatisticsFragment : Fragment() {

    private var _binding: FragmentStatisticsBinding? = null
    private val binding get() = _binding!!
    
    private lateinit var statisticsViewModel: StatisticsViewModel

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        statisticsViewModel = ViewModelProvider(this)[StatisticsViewModel::class.java]

        _binding = FragmentStatisticsBinding.inflate(inflater, container, false)
        val root: View = binding.root

        observeViewModel()

        return root
    }

    private fun observeViewModel() {
        statisticsViewModel.statistics.observe(viewLifecycleOwner) { stats ->
            binding.apply {
                textTodayOrders.text = stats.todayOrders.toString()
                textTodayRevenue.text = "¥${String.format("%.2f", stats.todayRevenue)}"
                textMonthOrders.text = stats.monthOrders.toString()
                textMonthRevenue.text = "¥${String.format("%.2f", stats.monthRevenue)}"
                textTotalOrders.text = stats.totalOrders.toString()
                textTotalRevenue.text = "¥${String.format("%.2f", stats.totalRevenue)}"
                textAverageRating.text = String.format("%.1f", stats.averageRating)
                
                // Update progress bars
                progressTodayOrders.progress = (stats.todayOrders * 10).coerceAtMost(100)
                progressMonthOrders.progress = (stats.monthOrders * 2).coerceAtMost(100)
            }
        }
        
        statisticsViewModel.isLoading.observe(viewLifecycleOwner) { isLoading ->
            binding.progressBar.visibility = if (isLoading) View.VISIBLE else View.GONE
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}
